package com.xiaoyg.receive;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @author xiaoyg
 * @Title: Receive
 * @ProjectName rabbitmq-helloworld
 * @Description: TODO
 * @date 2018/12/316:36
 */
public class Receive {

    //消息队列名称
    private final static String QUEUE_NAME = "helloworld";

    public static void main(String[] args) {

        //创建连接到RabbitMQ
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置RabbitMQ所在主机的IP或者主机名
        connectionFactory.setHost("192.168.8.129");
        //制定用户和密码
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("123456");
        //指定端口
        connectionFactory.setPort(AMQP.PROTOCOL.PORT);
        //创建一个连接
        try {
            Connection connection = connectionFactory.newConnection();
            //创建一个频道
            Channel channel = connection.createChannel();
            //指定一个队列
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);

            //创建队列消费者
            QueueingConsumer consumer = new QueueingConsumer(channel);
            //指定消费队列
            channel.basicConsume(QUEUE_NAME,true,consumer);

            while (true){
                //nextDelivery是一个阻塞方法（内部实现其实是阻塞队列的take方法）
                QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                String message = new String(delivery.getBody());
                System.out.println("Received Message:'"+message+"'");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}
